<template>
  <el-card shadow="hover" class="query-form-card">
    <template #header>
      <div class="card-header">
        <el-icon style="display: inline; vertical-align: middle"> <ele-Search /> </el-icon>
        <span>查询筛选</span>
      </div>
    </template>

    <el-form :model="queryParams" ref="queryForm" label-width="64" style="padding-top: 16px;">
      <el-row :gutter="16" style="align-items: end;">
        <!-- 复合型：日期（左维度/右日期）。在大屏更紧凑：7/5/5/7 栅格，保证右侧按钮一排显示 -->
        <el-col :xs="24" :sm="24" :md="12" :lg="7" :xl="7">
          <el-form-item label="日期">
            <div class="date-comp">
              <div class="seg seg-left">
                <el-select class="dim-select" size="small" v-model="queryParams.periodType" placeholder="选择" @change="handlePeriodChange">
                  <el-option value="month" label="月" />
                  <el-option value="quarter" label="季" />
                  <el-option value="custom" label="自" />
                  <el-option value="year" label="年" />
                </el-select>
              </div>
              <div class="seg seg-right">
                <template v-if="queryParams.periodType === 'month'">
                  <el-date-picker size="small" type="month" v-model="tempMonth" value-format="YYYY-MM" placeholder="选择月份" :disabled-date="() => false" @change="applyMonth" />
                </template>
                <template v-else-if="queryParams.periodType === 'quarter'">
                  <div class="quarter-inline">
                    <el-date-picker size="small" class="year-ch" type="year" v-model="tempQuarterYear" value-format="YYYY" />
                    <el-select size="small" class="quarter-select" v-model="tempQuarter" placeholder="选择季度" @change="applyQuarterSelect">
                      <el-option :value="1" label="一季度" />
                      <el-option :value="2" label="二季度" />
                      <el-option :value="3" label="三季度" />
                      <el-option :value="4" label="四季度" />
                    </el-select>
                  </div>
                </template>
                <template v-else-if="queryParams.periodType === 'custom'">
                  <el-date-picker size="small" type="daterange" v-model="tempCustomRange" value-format="YYYY-MM-DD" start-placeholder="起始日期" end-placeholder="结束日期" unlink-panels range-separator="~" @change="applyCustomRange" />
                </template>
                <template v-else>
                  <el-date-picker size="small" type="year" v-model="tempYear" value-format="YYYY" placeholder="选择年份" @change="applyYear" />
                </template>
              </div>
            </div>
          </el-form-item>
        </el-col>

        <!-- 状态（隐藏） -->
        <el-col v-if="false" :xs="12" :sm="12" :md="6" :lg="4" :xl="4">
          <el-form-item label="状态">
            <el-radio-group v-model="queryParams.planStart" @change="handleQuery" style="width: 100%">
              <el-radio-button :value="false">未完成</el-radio-button>
              <el-radio-button :value="true">已完成</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <!-- 分类：更紧凑，固定控件宽度以统一视觉 -->
        <el-col :xs="24" :sm="24" :md="6" :lg="5" :xl="5">
          <el-form-item label="分类">
            <el-select size="small" clearable filterable v-model="queryParams.className" placeholder="请选择分类" @change="handleQuery" style="width: 220px">
              <el-option v-for="(item, index) in dropdownData.className" :key="index" :value="item.value" :label="item.label" />
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 区域：更紧凑，固定控件宽度以统一视觉 -->
        <el-col :xs="24" :sm="24" :md="6" :lg="5" :xl="5">
          <el-form-item label="区域">
            <el-select size="small" clearable filterable v-model="queryParams.workAreaId" placeholder="请选择区域" @change="handleQuery" style="width: 220px">
              <el-option v-for="(item, index) in dropdownData.workAreaId" :key="index" :value="item.value" :label="item.label" />
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 操作按钮：lg/xl 提宽到 7，确保 3 个按钮同行显示 -->
        <el-col :xs="24" :sm="24" :md="24" :lg="7" :xl="7">
          <el-form-item>
            <div style="display: flex; justify-content: flex-end; width: 100%; gap: 8px; flex-wrap: nowrap;">
              <el-button-group>
                <el-button size="small" type="primary" icon="ele-Search" @click="handleQuery">查询</el-button>
                <el-button size="small" icon="ele-Refresh" @click="handleReset">重置</el-button>
                <el-button size="small" type="warning" icon="ele-FullScreen" @click="handleGoToDelayBoard">全屏延期看板</el-button>
              </el-button-group>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from 'vue';
import { useRouter } from 'vue-router';

interface DropdownData {
  className: Array<{ value: number | null; label: string }>;
  workAreaId: Array<{ value: number | null; label: string }>;
}

interface QueryParams {
  workTime: string; // 兼容保留
  periodType?: 'month' | 'quarter' | 'custom' | 'year';
  year?: string; // YYYY
  quarter?: number; // 1-4
  quarterMonth?: string; // YYYY-MM（季度末月）
  rangeStart?: string;
  rangeEnd?: string;
  className: number | null;
  workAreaId: number | null;
  keyword: string;
  advancedField: string;
  planStart: boolean;
}

interface Props {
  dropdownData: DropdownData;
  initialQueryParams: QueryParams;
}

interface Emits {
  (e: 'query', params: QueryParams): void;
  (e: 'reset'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();
const router = useRouter();

const queryParams = reactive<QueryParams>({ ...props.initialQueryParams });

// 弹层与临时状态
// tempPeriodType 已在上方定义
const tempMonth = ref<string>('');
const tempYear = ref<string>('');
const tempQuarterYear = ref<string>(new Date().getFullYear().toString());
const tempCustomRange = ref<[string, string] | null>(null);
// 复合控件：左侧维度切换
const tempPeriodType = ref<'month' | 'quarter' | 'custom' | 'year'>(queryParams.periodType || 'month');
const handlePeriodTypeChange = (val: 'month' | 'quarter' | 'custom' | 'year') => {
  queryParams.periodType = val;
  if (val === 'month') {
    queryParams.year = undefined; queryParams.quarter = undefined; queryParams.quarterMonth = undefined;
    // 不立即查询，等待选择月份
  } else if (val === 'quarter') {
    queryParams.workTime = '';
    queryParams.year = undefined; queryParams.quarter = undefined; queryParams.quarterMonth = undefined;
  } else if (val === 'custom') {
    queryParams.workTime = '';
    queryParams.year = undefined; queryParams.quarter = undefined; queryParams.quarterMonth = undefined;
    queryParams.rangeStart = undefined; queryParams.rangeEnd = undefined;
  } else if (val === 'year') {
    queryParams.workTime = '';
    queryParams.quarterMonth = undefined; queryParams.quarter = undefined;
  }
};

// 与模板中 @change 对齐的别名（避免未定义错误）
const handlePeriodChange = (val: 'month' | 'quarter' | 'custom' | 'year') => handlePeriodTypeChange(val);

// 格式化ISO本地时间
const formatLocal = (date: Date): string => {
  const pad = (n: number) => String(n).padStart(2, '0');
  const yyyy = date.getFullYear();
  const MM = pad(date.getMonth() + 1);
  const dd = pad(date.getDate());
  const hh = pad(date.getHours());
  const mm = pad(date.getMinutes());
  const ss = pad(date.getSeconds());
  const ms = String(date.getMilliseconds()).padStart(3, '0');
  return `${yyyy}-${MM}-${dd}T${hh}:${mm}:${ss}.${ms}`;
};

// 计算业务范围：月/季/年（26→25）
const computeBusinessRange = () => {
  const type = queryParams.periodType || 'month';
  if (type === 'month') {
    const [y, m] = (queryParams.workTime || '').split('-').map((s) => parseInt(s, 10));
    if (!y || !m) return;
    const target = new Date(y, m - 1, 1);
    const prev = new Date(y, m - 2, 1);
    queryParams.rangeStart = formatLocal(new Date(prev.getFullYear(), prev.getMonth(), 26, 0, 0, 0, 0));
    queryParams.rangeEnd = formatLocal(new Date(target.getFullYear(), target.getMonth(), 25, 23, 59, 59, 999));
    return;
  }
  if (type === 'year') {
    const y = parseInt(queryParams.year || '', 10);
    if (!y) return;
    queryParams.rangeStart = formatLocal(new Date(y - 1, 11, 26, 0, 0, 0, 0));
    queryParams.rangeEnd = formatLocal(new Date(y, 11, 25, 23, 59, 59, 999));
    queryParams.workTime = `${y}-12`;
    return;
  }
  if (type === 'quarter') {
    if (queryParams.quarterMonth) {
      const [y, m] = queryParams.quarterMonth.split('-').map((s) => parseInt(s, 10));
      let start: Date, end: Date;
      if (m === 3) { start = new Date(y - 1, 11, 26, 0, 0, 0, 0); end = new Date(y, 2, 25, 23, 59, 59, 999); }
      else if (m === 6) { start = new Date(y, 2, 26, 0, 0, 0, 0); end = new Date(y, 5, 25, 23, 59, 59, 999); }
      else if (m === 9) { start = new Date(y, 5, 26, 0, 0, 0, 0); end = new Date(y, 8, 25, 23, 59, 59, 999); }
      else if (m === 12) { start = new Date(y, 8, 26, 0, 0, 0, 0); end = new Date(y, 11, 25, 23, 59, 59, 999); }
      else return;
      queryParams.rangeStart = formatLocal(start);
      queryParams.rangeEnd = formatLocal(end);
      queryParams.workTime = `${y}-${String(m).padStart(2, '0')}`;
      return;
    }
    const y = parseInt(queryParams.year || '', 10);
    const q = queryParams.quarter || 0;
    if (!y || !q) return;
    let start: Date, end: Date;
    if (q === 1) { start = new Date(y - 1, 11, 26, 0, 0, 0, 0); end = new Date(y, 2, 25, 23, 59, 59, 999); }
    else if (q === 2) { start = new Date(y, 2, 26, 0, 0, 0, 0); end = new Date(y, 5, 25, 23, 59, 59, 999); }
    else if (q === 3) { start = new Date(y, 5, 26, 0, 0, 0, 0); end = new Date(y, 8, 25, 23, 59, 59, 999); }
    else if (q === 4) { start = new Date(y, 8, 26, 0, 0, 0, 0); end = new Date(y, 11, 25, 23, 59, 59, 999); }
    else return;
    queryParams.rangeStart = formatLocal(start);
    queryParams.rangeEnd = formatLocal(end);
    queryParams.workTime = `${y}-${q === 1 ? '03' : q === 2 ? '06' : q === 3 ? '09' : '12'}`;
  }
};

// 统一显示
const timeDisplay = computed(() => {
  const cn = (q?: number) => q === 1 ? '一季度' : q === 2 ? '二季度' : q === 3 ? '三季度' : q === 4 ? '四季度' : '';
  if (queryParams.periodType === 'month' && queryParams.workTime) return `${queryParams.workTime}`;
  if (queryParams.periodType === 'quarter' && queryParams.year && queryParams.quarter) return `${queryParams.year} ${cn(queryParams.quarter)}`;
  if (queryParams.periodType === 'custom' && queryParams.rangeStart && queryParams.rangeEnd) return `${queryParams.rangeStart.slice(0,10)} ~ ${queryParams.rangeEnd.slice(0,10)}`;
  if (queryParams.periodType === 'year' && queryParams.year) return `${queryParams.year}`;
  return '';
});

// 动态标签
const periodLabel = computed(() => {
  const t = queryParams.periodType || 'month';
  if (t === 'month') return '月份';
  if (t === 'quarter') return '季度';
  if (t === 'custom') return '范围';
  return '年份';
});

// 交互
const handleQuery = () => { emit('query', { ...queryParams }); };
const handleReset = () => {
  queryParams.className = null;
  queryParams.workAreaId = null;
  queryParams.rangeStart = undefined;
  queryParams.rangeEnd = undefined;
  queryParams.planStart = false;
  emit('reset');
};

const handleGoToDelayBoard = () => {
  // 延期看板为独立页面，不受当前页筛选影响
  router.push({ path: '/plans/delayBoard' });
};

// 应用月
const applyMonth = (val: string) => {
  if (!val) return;
  queryParams.periodType = 'month';
  queryParams.workTime = val;
  computeBusinessRange();
  handleQuery();
};
// 选择季度（下拉）
const tempQuarter = ref<number | null>(null);
const applyQuarterSelect = () => {
  const y = parseInt(tempQuarterYear.value || '', 10);
  const q = tempQuarter.value || 0;
  if (!y || !q) return;
  queryParams.periodType = 'quarter';
  queryParams.year = String(y);
  queryParams.quarter = q;
  queryParams.quarterMonth = `${y}-${q === 1 ? '03' : q === 2 ? '06' : q === 3 ? '09' : '12'}`;
  computeBusinessRange();
  handleQuery();
};
// 选季度
const pickQuarter = (q: number) => {
  const y = parseInt(tempQuarterYear.value || new Date().getFullYear().toString(), 10);
  const endMonth = q === 1 ? 3 : q === 2 ? 6 : q === 3 ? 9 : 12;
  queryParams.periodType = 'quarter';
  queryParams.year = String(y);
  queryParams.quarter = q;
  queryParams.quarterMonth = `${y}-${String(endMonth).padStart(2, '0')}`;
  computeBusinessRange();
  handleQuery();
};
// 应用年
const applyYear = (val: string) => {
  if (!val) return;
  queryParams.periodType = 'year';
  queryParams.year = val;
  computeBusinessRange();
  handleQuery();
};
// 自由范围
const applyCustomRange = () => {
  if (!tempCustomRange.value || tempCustomRange.value.length !== 2) return;
  const [sStr, eStr] = tempCustomRange.value;
  const s = new Date(sStr);
  const e = new Date(eStr);
  const pad = (n: number) => String(n).padStart(2,'0');
  const start = `${s.getFullYear()}-${pad(s.getMonth()+1)}-${pad(s.getDate())}T00:00:00.000`;
  const end = `${e.getFullYear()}-${pad(e.getMonth()+1)}-${pad(e.getDate())}T23:59:59.999`;
  queryParams.periodType = 'custom';
  queryParams.rangeStart = start;
  queryParams.rangeEnd = end;
  handleQuery();
};

const isSelectedQuarter = (q: number) => {
  if (queryParams.quarter && queryParams.year) return queryParams.quarter === q && queryParams.year === tempQuarterYear.value;
  if (queryParams.quarterMonth) {
    const [y, m] = queryParams.quarterMonth.split('-').map((s) => parseInt(s, 10));
    const endMonth = q === 1 ? 3 : q === 2 ? 6 : q === 3 ? 9 : 12;
    return String(y) === tempQuarterYear.value && m === endMonth;
  }
  return false;
};
</script>

<style scoped lang="scss">
.query-form-card {
  background: var(--el-bg-color);
  border-radius: 4px;
  border: 1px solid var(--el-border-color-light);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 8px;
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
  }

  .card-header {
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: 600;
    color: white;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 4px 4px 0 0;
    padding: 8px 20px;
    margin: -20px -20px 0px -20px;
    gap: 8px;
  }
}

@media (max-width: 768px) {
  .query-form-card {
    margin-bottom: 15px;

    .card-header { padding: 12px 15px; margin: -15px -15px 15px -15px; font-size: 14px; }
  }
}

/* 季度图片式样 */
.quarter-panel { display: flex; flex-direction: column; gap: 12px; }
.quarter-year { display: flex; align-items: center; gap: 8px; }
.quarter-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; }
.quarter-card { border: 1px solid var(--el-border-color); border-radius: 6px; padding: 6px 8px; text-align: center; cursor: pointer; background: linear-gradient(180deg, #f8fafc, #eef2f7); font-weight: 600; color: #303133; user-select: none; font-size: 12px; }
.quarter-card small { display:block; font-weight: 400; color: #909399; margin-top: 2px; font-size: 12px; }
.quarter-card:hover { border-color: var(--el-color-primary); box-shadow: 0 0 0 2px rgba(64,158,255,0.15) inset; }
.quarter-card.active { background: linear-gradient(180deg, #e8f3ff, #dbeafe); border-color: var(--el-color-primary); color: var(--el-color-primary); }

/* 自由筛选 */
.custom-panel { display:flex; align-items:center; gap:8px; }
.custom-panel .tilde { color:#909399; margin: 0 4px; }
.custom-tips { margin-top: 6px; color: #909399; font-size: 12px; }
.custom-actions { margin-top: 8px; }

/* 复合输入：隐藏中间输入区，去除多余边框，右侧容器自适应 */
.time-compact :deep(.el-input__wrapper) {
  padding: 0;
  border: none;
  box-shadow: none;
}
.time-compact :deep(.el-input__inner) { display: none; }
.time-compact :deep(.el-input-group__prepend) {
  padding: 0 8px;
  background: var(--el-bg-color);
  border-right: 1px solid var(--el-border-color);
}
.time-compact :deep(.el-input-group__append) {
  padding: 6px 8px;
  background: var(--el-bg-color);
  border-left: none;
}
.picker-wrap { display:inline-flex; align-items:center; gap:8px; }
.compact-select :deep(.el-input__wrapper) { padding: 0 8px; box-shadow: none; }

/* 复合时间控件布局 */
.time-composite { display: flex; align-items: center; gap: 8px; }
.quarter-inline { display: flex; align-items: center; gap: 6px; width: 100%; }
.year-ch { width: 84px; }
.quarter-select { flex: 1 1 auto; }

/* 复合输入边框与比例 */
.date-comp { display: flex; width: 280px; border: none; border-radius: 0; overflow: visible; gap: 8px; }
.date-comp .seg { display: flex; align-items: center; padding: 0; }
.date-comp .seg-left { flex: 0 0 auto; border-right: none; }
.date-comp .seg-right { flex: 1 1 auto; min-width: 0; }
.dim-select { width: 5.2em; }
.date-comp.single :deep(.el-input__wrapper) { border: none; box-shadow: none; padding: 0 8px; }
.date-comp.single :deep(.el-input__inner) { padding: 0; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.date-comp.single :deep(.el-select .el-input__wrapper) { padding: 0 8px; }
.date-comp :deep(.el-date-editor) { width: 100%; }

/* 去掉左右控件之间的缝隙，并让它们看起来像一个整体 */
/* 维度选择与日期之间恢复独立圆角，保留 8px 间距 */
.date-comp .seg-left :deep(.el-input__wrapper) {
  border-top-right-radius: var(--el-border-radius-base);
  border-bottom-right-radius: var(--el-border-radius-base);
  border-right: 1px solid var(--el-border-color);
}
.date-comp .seg-right :deep(.el-input__wrapper) {
  border-top-left-radius: var(--el-border-radius-base);
  border-bottom-left-radius: var(--el-border-radius-base);
}
</style>
